package service

import (
	"batbat-backend/app/model"
	"batbat-backend/library/captcha"
	"context"
	"github.com/gogf/gf/errors/gerror"
	"github.com/gogf/gf/frame/g"
	"github.com/mojocn/base64Captcha"
)

// Captcha 验证码服务
var Captcha = captchaService{
	driver: &base64Captcha.DriverString{
		Height:          35,
		Width:           70,
		NoiseCount:      30,
		ShowLineOptions: base64Captcha.OptionShowHollowLine,
		Length:          4,
		Source:          "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM123456789",
	},
	store: &captcha.RedisStore, // 使用自定义的redis缓存
}

type captchaService struct {
	driver base64Captcha.Driver
	store  base64Captcha.Store
}

// GenerateCaptcha 生成验证码
func (c *captchaService) GenerateCaptcha(ctx context.Context) (*model.CaptchaServiceGenerateResp, error) {
	id, b64s, err := base64Captcha.NewCaptcha(c.driver, c.store).Generate()
	if err != nil {
		g.Log().Ctx(ctx).Errorf("生成验证码失败: %v", err)
		return nil, gerror.New("生成验证码失败")
	}
	return &model.CaptchaServiceGenerateResp{Id: id, Captcha: b64s}, nil
}

// VerifyCaptcha 校验验证码, 校验完成后会从内存中删除
func (c *captchaService) VerifyCaptcha(ctx context.Context, id string, ans string) bool {
	return c.store.Verify(id, ans, true)
}
